#include <iostream>
#include "../common/httplib.h"
#include "oj_control.hpp"
#include <signal.h>

using namespace httplib;
using namespace ns_control;

static Control* ctrl_ptr = nullptr;

void Recovery(int signo)
{
    ctrl_ptr->RecoverAllHost();
}

int main()
{
    signal(SIGQUIT, Recovery);
    // 用户请求的路由功能，统一交给 ctrl去做
    Server svr;
    Control ctrl;
    ctrl_ptr = &ctrl;

    // 1. 获取题目列表
    svr.Get(R"(/all_questions)", [&ctrl](const Request& req, Response& resp){
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html, "text/html;charset=utf-8");
    });

    // 2. 获取单个题目的编辑页面，用户根据题号，获取题目内容
    // /question/100: 使用正则表达式获取
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request& req, Response& resp){
        std::string num = req.matches[1];
        std::string html;
        ctrl.OneQuestion(num, &html);
        resp.set_content(html, "text/html;charset=utf-8");
    });

    // 3. 用户点击提交代码，使用我们的判题功能（每道题的测试用例、compile_and_run）
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request& req, Response& resp){
        std::string num = req.matches[1];
        std::string out_json;
        ctrl.Judge(num, req.body, &out_json);
        resp.set_content(out_json, "application/json;charset=utf-8");
        // resp.set_content("指定题目的判题：" + num, "text/html;charset=utf-8");
    });
    
    // 设置网站的根目录
    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0", 8080);
    return 0;
}